package cn.iocoder.yudao.module.system.service.task;

import cn.iocoder.yudao.module.system.controller.admin.task.vo.TaskStatusRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.task.UserTaskRecordDO;
import cn.iocoder.yudao.module.system.dal.mysql.task.UserTaskRecordMapper;
import cn.iocoder.yudao.module.system.enums.task.TaskTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户任务 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class UserTaskServiceImpl implements UserTaskService {

    @Resource
    private UserTaskRecordMapper userTaskRecordMapper;

    @Override
    public boolean completeShareTask(Long userId) {
        return completeTask(userId, TaskTypeEnum.SHARE_TASK);
    }

    @Override
    public boolean completeInviteFriendTask(Long userId) {
        return completeTask(userId, TaskTypeEnum.INVITE_FRIEND);
    }

    @Override
    public boolean completeProfileTask(Long userId) {
        return completeTask(userId, TaskTypeEnum.COMPLETE_PROFILE);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeTask(Long userId, TaskTypeEnum taskType) {
        // 检查今日是否已完成该任务
        if (hasCompletedTaskToday(userId, taskType)) {
            log.info("用户{}今日已完成任务类型{}", userId, taskType.getName());
            return false;
        }

        // 创建任务记录
        UserTaskRecordDO record = UserTaskRecordDO.builder()
                .userId(userId)
                .taskType(taskType.getType())
                .taskName(taskType.getName())
                .completeTime(LocalDateTime.now())
                .rewardLotteryCount(1) // 每个任务奖励1次抽奖机会
                .rewarded(true) // 自动发放奖励
                .rewardTime(LocalDateTime.now())
                .remark("完成" + taskType.getName() + "获得1次抽奖机会")
                .build();

        userTaskRecordMapper.insert(record);
        log.info("用户{}完成任务{}，获得{}次抽奖机会", userId, taskType.getName(), record.getRewardLotteryCount());
        return true;
    }

    @Override
    public boolean hasCompletedTaskToday(Long userId, TaskTypeEnum taskType) {
        LocalDateTime startOfDay = LocalDateTime.now().with(LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.now().with(LocalTime.MAX);
        
        Long count = userTaskRecordMapper.countTodayTaskByUserIdAndType(
                userId, taskType.getType(), startOfDay, endOfDay);
        
        return count > 0;
    }

    @Override
    public int getTodayTaskLotteryCount(Long userId) {
        LocalDateTime startOfDay = LocalDateTime.now().with(LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.now().with(LocalTime.MAX);
        
        Integer count = userTaskRecordMapper.sumTodayRewardLotteryCount(userId, startOfDay, endOfDay);
        return count != null ? count : 0;
    }

    @Override
    public List<UserTaskRecordDO> getUserTaskRecords(Long userId) {
        return userTaskRecordMapper.selectListByUserId(userId);
    }

    @Override
    public List<TaskStatusRespVO> getUserTaskStatus(Long userId) {
        List<TaskStatusRespVO> taskStatusList = new ArrayList<>();

        // 遍历所有任务类型
        for (TaskTypeEnum taskType : TaskTypeEnum.values()) {
            TaskStatusRespVO taskStatus = new TaskStatusRespVO();
            taskStatus.setTaskType(taskType.getType());
            taskStatus.setTaskName(taskType.getName());
            taskStatus.setTaskDescription(taskType.getDescription());
            taskStatus.setCompletedToday(hasCompletedTaskToday(userId, taskType));
            taskStatus.setRewardLotteryCount(1); // 每个任务奖励1次抽奖机会

            taskStatusList.add(taskStatus);
        }

        return taskStatusList;
    }
}
